package br.com.conciliador.util;

import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.activation.FileTypeMap;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.export.JExcelApiExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.export.JExcelApiExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;

import br.com.conciliador.download.vo.ExportarDownloadVo;
import br.com.r2.exception.R2Exception;

public class Download
{

   public static synchronized void gerarArquivo(HttpServletResponse response, String caminho, String nomeArquivo) throws R2Exception
   {
      File arquivo = new File(caminho, nomeArquivo);

      try
      {
         if (arquivo != null && arquivo.isFile())
         {
            String contentType = FileTypeMap.getDefaultFileTypeMap().getContentType(arquivo);

            response.setContentType(contentType);
            response.addHeader("Content-Disposition", "attachment; filename=" + nomeArquivo);
            response.setContentLength((int) arquivo.length());

            FileInputStream in = new FileInputStream(arquivo);
            OutputStream out = response.getOutputStream();

            byte[] buf = new byte[(int) arquivo.length()];
            int count;
            while ((count = in.read(buf)) >= 0)
            {
               out.write(buf, 0, count);
            }
            in.close();
            out.flush();
            out.close();
         }
         else
         {
            throw new R2Exception("erro.arquivo.nao.encontrado");
         }
      }
      catch (IOException ioe)
      {
         throw new R2Exception(ioe);
      }
   }

   public static void gerarArquivoZip(HttpServletResponse response, String caminho, String nomeArquivo) throws R2Exception
   {
      File arquivo = new File(caminho, nomeArquivo);
      try
      {
         if (arquivo != null && arquivo.isFile())
         {
            // response.setContentType("application/download");
            // response.setHeader("Content-Disposition", (new
            // StringBuilder()).append("attachment; filename=\"").append(nomeArquivo).append(".zip\"").toString());
            String contentType = FileTypeMap.getDefaultFileTypeMap().getContentType(arquivo);

            response.setContentType(contentType);
            response.addHeader("Content-Disposition", "attachment; filename=" + nomeArquivo);
            ZipOutputStream outputStream = new ZipOutputStream(response.getOutputStream());
            InputStream inputStream = new BufferedInputStream(new FileInputStream(arquivo));
            outputStream.putNextEntry(new ZipEntry(nomeArquivo));
            int charInput;
            while ((charInput = inputStream.read()) != -1)
            {
               outputStream.write(charInput);
            }
            outputStream.close();
            inputStream.close();
         }
         else
         {
            throw new R2Exception("erro.arquivo.nao.encontrado");
         }
      }
      catch (IOException ioe)
      {
         throw new R2Exception(ioe);
      }
   }

   public static void exportarArquivo(ExportarDownloadVo exportarDownloadVo) throws R2Exception
   {

      FileWriter writer = null;
      PrintWriter saida = null;

      try
      {
         writer = new FileWriter(new File(exportarDownloadVo.getCaminhoDestino(), exportarDownloadVo.getNomeArquivoDestino()));
         saida = new PrintWriter(new BufferedWriter(writer, 1 * 1024 * 1024));

         String caminhoCompleto = exportarDownloadVo.getCaminhoOrigem()
                                  + File.separator
                                  + exportarDownloadVo.getNomeArquivoOrigem();

         Arquivo arquivo = new Arquivo();
         // arquivo.abrir(caminhoCompleto, true);
         arquivo.ler(caminhoCompleto);
         String linha = "";
         while ((linha = arquivo.getLinha()) != null)
         {
            saida.print(linha);
            saida.print("\n");
         }
      }
      catch (IOException e)
      {
         throw new R2Exception(e);
      }
      finally
      {
         if (saida != null)
         {
            saida.close();
         }
         if (writer != null)
         {
            try
            {
               writer.close();
            }
            catch (IOException e)
            {
               throw new R2Exception(e);
            }
         }
      }
   }

   public static void gerarExcel(byte[] bytes, HttpServletResponse response, String nomeArquivoGerado) throws R2Exception
   {
      if (bytes != null && bytes.length > 0)
      {
         response.setContentType("application/vnd.ms-excel");
         response.setHeader("content-Disposition", "attachment; filename=" + nomeArquivoGerado);
         response.setContentLength(bytes.length);
         try
         {
            ServletOutputStream ouputStream = response.getOutputStream();
            ouputStream.write(bytes, 0, bytes.length);
            ouputStream.flush();
            ouputStream.close();
         }
         catch (IOException ioe)
         {
            throw new R2Exception(ioe);
         }
      }
   }

   public static byte[] exportarExcel(JasperPrint jasperPrint) throws R2Exception
   {
      try
      {
         JExcelApiExporter jExcelExporter = new JExcelApiExporter();
         ByteArrayOutputStream xlsReport = new ByteArrayOutputStream();
         jExcelExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
         jExcelExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, xlsReport);
         jExcelExporter.setParameter(JRXlsExporterParameter.IS_DETECT_CELL_TYPE, Boolean.TRUE);
         jExcelExporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
         jExcelExporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
         jExcelExporter.exportReport();

         byte[] bs = xlsReport.toByteArray();

         xlsReport.close();

         return bs;
      }
      catch (IOException e)
      {
         throw new R2Exception(e);
      }
      catch (JRException e)
      {
         throw new R2Exception(e);
      }
   }

}
